<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-payBack-wrap">
    <explanation :explanation="explanationObj" is-expand class="explanation" style="margin: 0;"/>
    <div class="page-container">
      <Title title="基础信息" style="margin-bottom: 16px;" />
      <el-form
        ref="baseform"
        :rules="rules"
        :model="paramsObj"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="105px">
        <el-row class="response-el-row" type="flex">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请人" prop="applicantId">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="paramsObj.proposerObj"
                :hide-select-list="paramsObj.applicantId && paramsObj.applicant?[{id: paramsObj.applicantId, userName: paramsObj.applicant}] : []"
                :multiple="false"
                :value-type="'object'"
                :show-check-user="true"
                key-name="id"
                class="width240"
                label-name="userName"
                filterable
                @change="proposerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="申请部门" prop="applyDepartmentId">
              <el-cascader
                v-model="paramsObj.applyDepartmentId"
                :show-all-levels="false"
                :options="deptTreeList"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                filterable
                class="width240"
                placeholder="请选择申请部门"
                size="small"
              >
                <template slot-scope="{ data }">
                  <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                    <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                    <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                  </el-tooltip>
                  <span v-else>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="所属公司" prop="company">
              <el-select v-model="paramsObj.company" filterable size="small" class="width240" popper-class="panel-auto-width" placeholder="请选择">
                <el-option
                  v-for="item in companies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="借款周期" prop="loanDateRange">
              <el-date-picker
                v-model="paramsObj.loanDateRange"
                type="daterange"
                align="right"
                size="small"
                class="width240"
                value-format="timestamp"
                unlink-panels
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy/MM/dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="借款说明" prop="remark">
              <el-input v-model="paramsObj.remark" :maxlength="500" class="width240" placeholder="请输入借款说明" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="借款金额(元)" prop="amount">
              <el-input
                v-model="paramsObj.amount"
                :min="0"
                size="small"
                type="number"
                class="width240"
                placeholder="请输入借款金额"
                oninput="if(value>999999999)value=999999999"
                @input="numInputChange($event, 'amount')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="附件" prop="attachment">
              <upAttachment
                ref="uploadImg"
                :import-api="'/common/file/upload'"
                :hide-confirm="true"
                :is-disabled="false"
                :file-list="paramsObj.attachment"
                :limit="99999"
                btn-text="上传附件"
                @upProgress="upProgress"
                @complateSetData="complateSetData"
                @removeFileList="removeFileList"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Title title="收款账户" style="margin: 8px 0 16px;" />
      <dynamicEditTable
        v-if="flag"
        ref="dynamicPayerTable"
        v-model="accountInfo"
        :list-data="accountInfo"
        :list-setting="accountSetting"
        :is-edit="true"
        :show-add-btn="false"
        :show-delete-btn="false"
        :show-copy-btn="false"
        :is-fill="false"
        :show-serial="false"
        @createNewItem="addNewBank"
        @autocompleteDelFn="autocompleteDelFn"
        @autocompleteSelect="autocompleteSelect"
      />
    </div>
    <audit-process
      ref="auditProcessRef"
      :loading="btnLoading"
      v-model="auditInfo"
      :old-audit-info="oldAuditInfo"
      :default-aduitor-list="[{id: paramsObj.applicantId, userName: paramsObj.applicant}]"

      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="toSubmit(SUBMITTYPE.SUBMIT,$event)"
      @getProcess="getProcess" />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="(!remodifyId && !reapplyId) || createNew" :loading="btnLoading" type="primary" size="small" plain class="empty-btn-style" @click="toSubmit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import Title from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import upAttachment from '@/components/Common/upAttachment/index';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import { isContained } from '@/utils/tools';
import { submitLoanForm, getLoanDetail, createLoan, editLoan } from '@/api/loan';
import { getDepartmentAll } from '@/api/config';
import { processManagementDetail } from '@/api/legal';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { SUBMITTYPE } from '@/utils/const/cost';
import { createAuditStructure } from '@/utils/aduitor';
import ElMessage, { showModal } from '@/utils/message';
import accountTable from '@/mixins/accountTable';
import accountBackfill from '@/mixins/accountBackfill';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, selectWithUserLoad, upAttachment, AuditProcess, explanation, dynamicEditTable },
  mixins: [accountTable, accountBackfill, processCreate, mobileCreate],
  data() {
    return {
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      rules: {
        'applicantId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'applyDepartmentId': [{ required: true, message: '请选择申请部门', trigger: 'change' }],
        'company': [{ required: true, message: '请选择所属公司', trigger: 'change' }],
        'loanDateRange': [{ required: true, message: '请选择借款周期', trigger: 'change' }],
        'remark': [{ required: true, message: '请输入借款说明', trigger: 'blur' }],
        'amount': [{ required: true, message: '请输入借款金额', trigger: 'blur' }]
      },
      SUBMITTYPE,
      createLoading: false,
      btnLoading: false,
      isEdit: false,
      paramsObj: {
        proposerObj: {},
        applicantId: '',
        applicant: '',
        deptId: '',
        attachment: [],
        amount: '',
        loanDateRange: [],
        company: ''
      },
      loanId: '',
      deptTreeList: [],
      // 流程信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      processDetail: null,
      remodifyId: null, // 修改，审批流程不能修改
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      companies: [],
      accountInfo: [{
        payName: '',
        payNum: '',
        bank: '',
        province: '',
        subBank: ''
      }],
      processId: null,
      isRefresh: false,
      createNew: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    accountSetting() {
      return [{
        label: '收款户名',
        type: 'inputText',
        width: '150px',
        isRequired: true,
        canDelBtn: true,
        keyword: 'payName',
        queryName: 'queryString'
      }, {
        label: '收款账号',
        type: 'inputText',
        width: '150px',
        isRequired: true,
        keyword: 'payNum'
      }, {
        label: '银行',
        type: 'select',
        keyName: 'value',
        isRequired: true,
        keyword: 'bank',
        tip: '输入系统中未添加的银行名称时将自动添加该银行',
        options: this.bankList,
        placeholder: '请选择',
        createNew: true },
      {
        label: '省市',
        type: 'selectCity',
        isRequired: true,
        selectType: 'city',
        separator: '-',
        width: '160px',
        placeholder: '请选择省-市',
        keyword: 'province'
      }, {
        label: '支行',
        type: 'inputText',
        width: '150px',
        isRequired: true,
        keyword: 'subBank'
      }];
    }
  },
  created() {
    this.getCompany();
    this.queryDeptTreeList();
    this.getBankList();// 银行名称列表
    this.loanId = Number(this.$route.params.id) || '';
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.remodifyId = this.$route.query.remodifyId; // 修改
    this.reapplyId = this.$route.query.reapplyId; // 重新申请
    if (this.loanId) {
      this.isEdit = true;
      this.getDetail();
      this.reapplyId && this.getExplanation();
    } else {
      if (this.userInfo.deptName && this.userInfo.deptName.length > 0) {
        this.paramsObj.applyDepartmentId = this.getFirstDepartment(this.userInfo.departmentAry);
      }
      this.paramsObj.applicantId = this.userInfo.id;
      this.paramsObj.applicant = this.userInfo.userName;
      this.paramsObj.proposerObj = {
        id: this.userInfo.id,
        userName: this.userInfo.userName
      };
      this.isEdit = false;
      this.getExplanation();
      this.fillAccountInfo();
    }
  },
  methods: {
    // // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        return Array.isArray(deptIdArr) && deptIdArr.length ? deptIdArr[deptIdArr.length - 1] : null;
      } else {
        return null;
      }
    },
    // 获取所属公司数据
    getCompany() {
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          const result = [];
          res.data.forEach(item => {
            result.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
          this.companies = result;
        }
      });
    },
    // 限制借款金额
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.paramsObj[prop] = str;
    },
    proposerChange(data) {
      this.paramsObj.applicantId = data.id;
      this.paramsObj.applicant = data.userName;
      this.paramsObj.avatar = data.avatar;
    },
    getExplanation() { // 获取审批说明
      // 借款申请type为18
      processManagementDetail({ id: 3527, type: 18 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    backfillBank(name) {
      this.accountInfo[0].bank = name;
    },
    getDetail() {
      getLoanDetail({ id: this.loanId }).then(res => {
        if (res.code === 200) {
          this.paramsObj = res.data;
          if (res.data.loanStartDate) {
            this.$set(this.paramsObj, 'loanDateRange', [res.data.loanStartDate, res.data.loanEndDate]);
          }
          this.accountInfo = res.data.accountInfo;
          if (this.paramsObj.amount || this.paramsObj.amount === 0) {
            this.paramsObj.amount /= 100;
          }
          this.paramsObj.proposerObj = {
            id: this.paramsObj.applicantId,
            userName: this.paramsObj.applicant
          };
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          if (this.loanId) {
            this.$refs.baseform.resetFields();
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      });
    },
    handleParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (params.loanDateRange && params.loanDateRange.length > 0) {
        params.loanStartDate = params.loanDateRange[0] / 1000;
        params.loanEndDate = params.loanDateRange[1] / 1000;
      }
      delete params.loanDateRange;
      params.accountInfo = this.accountInfo;
      if (params.amount || params.amount === 0) {
        params.amount *= 100;
      }
      return params;
    },
    toSubmit(submitType = SUBMITTYPE.SUBMIT, senders = []) {
      this.modifySenders = senders;// 存到mixins
      // 处理参数
      const params = this.handleParams();
      params.submitType = submitType;
      if (submitType !== SUBMITTYPE.DRAFT && this.reapplyId && !this.createNew) { // 重新提交
        params.submitType = SUBMITTYPE.RESUBMIT;
      }
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      if (this.createNew) {
        delete params.id;
      }
      params.auditInfo = this.auditInfo;
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      if (this.isEdit && !this.createNew) {
        showModal(msg).then(() => {
          this.handleModifyData(params);
          this.edit(params);
        });
      } else {
        showModal(msg).then(() => this.create(params));
      }
    },
    // 流程相关 start
    openDrawer() { // 流程弹窗
      try {
        const params = [];
        params.push(this.$refs.baseform.validate());
        params.push(this.$refs.dynamicPayerTable.validate());
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            this.getProcessDetail();
          } else {
            return false;
          }
        }).catch((error) => {
          ElMessage.warning('请检查信息是否填写完整');
          console.log('error', error);
        });
      } catch (error) {
        console.log(error);
      }
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    getProcessDetail(isRefresh) {
      const params = this.handleParams();
      params.type = 18; // 流程类型，借款申请
      this.btnLoading = true;
      submitLoanForm(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcessRef'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = {
              id: this.paramsObj.applicantId,
              userName: this.paramsObj.applicant,
              avatar: this.paramsObj.avatar
            };
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcessRef'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    // 流程相关 end
    create(params) {
      this.btnLoading = true;
      createLoan(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'loanDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        this.btnLoading = false;
      });
    },
    edit(params) {
      this.btnLoading = true;
      editLoan(this.loanId, params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.processId) {
            this.$router.push({
              name: 'loanDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'loanDetail', params: {}, query: { id: this.loanId, processId: this.remodifyId }});
        }
        this.btnLoading = false;
      });
    },
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      !this.paramsObj.attachment && (this.paramsObj.attachment = []);
      this.paramsObj.attachment.push(fileList);
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'loanDetail',
          query: {
            id: this.id,
            processId: this.processId
          }
        });
        return;
      }
      this.$router.push({
        name: 'loan'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-payBack-wrap{
  .width240 {
    width: 240px;
  }
  .page-container{
    padding: 20px 24px 24px;
  }
	margin: 16px;
	background: #FFFFFF;
	min-height: calc(100vh - 56px);
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    width: 80px;
    padding: 7px 0;
    text-align: center;
  }
  .explanation{
    padding-left: 9px;
  }
  .all-ratio{
    height: 32px;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-left: 8px;
    padding: 0 21px 0 4px;
    background: #FAFAFC;
    border-radius: 2px;
    .text{
      font-size: 16px;
      color: #5F77C3;
    }
  }
  ::v-deep .el-range-separator{
    width: 20px;
  }
}
::v-deep .el-cascader--large {
  width: 100%;
}
</style>
